package com.media.entrance.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.media.entrance.model.*;
import com.media.entrance.service.MediaAgentService;
import com.media.entrance.service.RedisService;
import com.media.entrance.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.websocket.Session;

// 二期坐席端接口
@Controller
@Slf4j
@RequestMapping("/agent")
public class AgentController {

    @Autowired
    private MediaAgentService mediaAgentService;

    @Autowired
    private RedisService redisService;

    private void formatResult(String info, BatchResultModel temp){
        try {
            // 序列化变成字符串
            String result = new ObjectMapper().writeValueAsString(temp);
            log.info(info + " return : [" +  result + "]");
        } catch (JsonProcessingException | IllegalStateException e) {
            log.error(info + " ：throw error" + temp, e);
        }
    }
    @ResponseBody
    @PostMapping("/login")
    public BatchResultModel login(@RequestBody JSONObject jsonParam) {
        log.info("/login receive : " +  jsonParam.toJSONString());
        BatchResultModel result;
        if (jsonParam.containsKey("agentId") && jsonParam.getJSONArray("agentId").size() > 0) {
            result = mediaAgentService.agentsLogin(jsonParam.getJSONArray("agentId"));
        } else {
            log.error("/login request body hasn't agentId or agentId array size = 0!" );
            result = new BatchResultModel("fail", "login requestbody hasn't agentId or agentId array size = 0!", null);
        }
        formatResult("/login", result);
        return result;
    }

    @ResponseBody
    @PostMapping("/logout")
    public BatchResultModel logout(@RequestBody JSONObject jsonParam) {
        log.info("/logout receive : " +  jsonParam.toJSONString());
        BatchResultModel result;
        if (jsonParam.containsKey("agentId") && jsonParam.getJSONArray("agentId").size() > 0) {
            result = mediaAgentService.agentsLogout(jsonParam.getJSONArray("agentId"));
        } else {
            log.error("/logout request body hasn't agentId or agentId array size = 0!" );
            result = new BatchResultModel("fail", "logout requestbody hasn't agentId or agentId array size = 0!", null);
        }
        formatResult("/logout", result);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getMatchResult/agentId={agentId}", method = RequestMethod.GET)
    public BatchResultModel getMatchResult(@PathVariable("agentId") String agentId) {
        BatchResultModel result;
        if (agentId == null) {
            result = new BatchResultModel("illegal input parameters", "agentId is null", null);
        } else {
            result = mediaAgentService.getAgentMatchResult(agentId);
        }
        formatResult("/getMatchResult/agentId=" + agentId, result);
        return result;
    }

    @ResponseBody
    @GetMapping("/getAgentIdByStatus/agentStatus={agentStatus}")
    public BatchResultModel getAgentIdByStatus(@PathVariable("agentStatus") String agentStatus) {
        BatchResultModel result;
        // 状态强校验
        String[] types = new String[]{"idle", "ring", "busy", "rest", "pause"};
        boolean flag = false;
        for (String string : types) {
            if (agentStatus.equals(string)){
                flag = true;
                break;
            }
        }
        if (flag) {
            result = mediaAgentService.getSameStatusAgents(agentStatus);
        } else {
            result = new BatchResultModel("fail", "agentStatus is illegal", null);
        }
        formatResult("/getAgentIdByStatus/agentStatus=" + agentStatus, result);
        return result;
    }

    @ResponseBody
    @PostMapping("/updateStatus")
    public BatchResultModel updateStatus(@RequestBody MatchInfo matchinfo) {
        log.info("updateStatus receive : " +  matchinfo);
        BatchResultModel result;
        if (matchinfo == null || matchinfo.getAgentId() == null || matchinfo.getAgentStatus() == null) {
            result =  new BatchResultModel("fail", "agentid or agentstatus is null", null);
        } else {
            // 状态强校验
            String[] types = new String[]{"idle", "ring", "busy", "rest", "pause"};
            boolean flag = false;
            for (String string : types) {
                if (matchinfo.getAgentStatus().equals(string)){
                    flag = true;
                    break;
                }
            }
            if (flag) {
                result = mediaAgentService.updateAgentsStatus(matchinfo);
            } else {
                result = new BatchResultModel("fail", "agentStatus is illegal", null);
            }
        }
        formatResult("/updateStatus", result);
        return result;
    }

    @ResponseBody
    @PostMapping("/inviteOther")
    public BatchResultModel inviteOther(@RequestBody JSONObject jsonObject) {
        log.info("inviteOther receive : " +  jsonObject.toJSONString());
        BatchResultModel result;
        if (jsonObject.containsKey("agentInfo") && jsonObject.getJSONArray("agentInfo").size() >= 1) {
            result = mediaAgentService.inviteOtherAgent(jsonObject.getJSONArray("agentInfo"));
        } else {
            result = new BatchResultModel("fail", "need agentInfo or agentInfo size is 0", null);
        }
        formatResult("/inviteOther", result);
        return result;
    }

    @ResponseBody
    @PostMapping("/routerOptions")
    public BatchResultModel setRouterOptions(@RequestBody JSONObject jsonObject) {
        BatchResultModel result;
        if (jsonObject.containsKey("queueLimit") && jsonObject.getIntValue("queueLimit") > 0) {
            result = mediaAgentService.setRouterOptions(jsonObject);
        } else {
            result = new BatchResultModel("fail", "queueLimit is not exist or value <= 0", null);
        }
        formatResult("/routerOptions", result);
        return result;
    }
}
